<template>
  <div class="unlock-container">
    <div class="header" :class="{ 'electron-header': isElectron }">
      <!-- 窗口控制按钮 -->
      <div class="window-controls" v-if="isElectron">
        <button 
          class="window-button window-button-close" 
          @click="handleWindowClose" 
          @mousedown.stop
          @mouseup.stop
          title="关闭"
        >
          <svg width="11" height="11" viewBox="0 0 12 12">
            <path d="M1 1L11 11M11 1L1 11" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
          </svg>
        </button>
        <button 
          class="window-button window-button-minimize" 
          @click="handleWindowMinimize" 
          @mousedown.stop
          @mouseup.stop
          title="最小化"
        >
          <svg width="11" height="11" viewBox="0 0 12 12">
            <path d="M2 6H10" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
          </svg>
        </button>
        <button 
          class="window-button window-button-maximize" 
          @click="handleWindowMaximize" 
          @mousedown.stop
          @mouseup.stop
          :title="isMaximized ? '还原' : '最大化'"
        >
          <svg v-if="!isMaximized" width="11" height="11" viewBox="0 0 12 12">
            <rect x="2" y="2" width="8" height="8" stroke="currentColor" stroke-width="1.5" fill="none"/>
          </svg>
          <svg v-else width="11" height="11" viewBox="0 0 12 12">
            <path d="M2 4H6V2M8 2V6H10" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" fill="none"/>
            <path d="M10 8H6V10M4 10V6H2" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" fill="none"/>
          </svg>
        </button>
      </div>
      <div class="header-content">
        <div class="logo-container">
          <canvas ref="logoCanvas" width="64" height="64"></canvas>
        </div>
        <h1>FLAC 音乐</h1>
        <p class="subtitle">简约 · 大气 · 无损</p>
      </div>
    </div>

    <div v-if="!isUnlocked" class="section">
      <div class="form-group">
        <label for="unlock-code">解锁码</label>
        <input 
          type="text" 
          id="unlock-code" 
          v-model="unlockCode"
          placeholder="请输入解锁码（有效期12小时）"
          autocomplete="off"
          @keypress.enter="handleUnlock"
        >
        <p class="hint">从微信公众号【黑话君】获取解锁码</p>
      </div>
      <button 
        id="unlock-btn" 
        class="btn btn-primary"
        :disabled="isVerifying"
        @click="handleUnlock"
      >
        {{ isVerifying ? '验证中...' : '确认解锁' }}
      </button>
      <div v-if="statusMessage" :class="['status-message', statusType]">
        {{ statusMessage }}
      </div>
    </div>

    <div v-else class="section">
      <div class="status-success">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M20 6L9 17l-5-5"></path>
        </svg>
        <span>已解锁</span>
      </div>
      <button 
        id="open-player-btn" 
        class="btn btn-primary btn-large"
        @click="$emit('open-player')"
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <polygon points="5 3 19 12 5 21 5 3"></polygon>
        </svg>
        打开播放器
      </button>
      <div class="info-text">
        <p>解锁码剩余时间：<span id="time-remaining">{{ timeRemaining }}</span></p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { storage } from '../utils/storage.js'
import { verifyUnlockCode } from '../utils/api.js'
import '../utils/logo-generator.js'

const props = defineProps({
  isElectron: {
    type: Boolean,
    default: false
  },
  isMaximized: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['open-player', 'window-minimize', 'window-maximize', 'window-close'])

const logoCanvas = ref(null)
const unlockCode = ref('')
const isUnlocked = ref(false)
const isVerifying = ref(false)
const statusMessage = ref('')
const statusType = ref('')
const timeRemaining = ref('--')
let timer = null

// 生成并显示 logo
onMounted(() => {
  if (logoCanvas.value && window.logoGenerator) {
    const logoDataUrl = window.logoGenerator.generateLogo(64)
    const img = new Image()
    img.onload = () => {
      const ctx = logoCanvas.value.getContext('2d')
      ctx.drawImage(img, 0, 0)
    }
    img.src = logoDataUrl
  }

  checkUnlockStatus()
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})

// 检查解锁状态
async function checkUnlockStatus() {
  const result = await storage.get(['unlockCode', 'unlockTime', 'isUnlocked'])
  
  if (result.isUnlocked && result.unlockTime) {
    const unlockTime = result.unlockTime
    const now = Date.now()
    const elapsed = now - unlockTime
    const remaining = 12 * 60 * 60 * 1000 - elapsed

    if (remaining > 0) {
      isUnlocked.value = true
      updateTimeRemaining(remaining)
      
      // 每秒更新一次倒计时
      timer = setInterval(() => {
        const newRemaining = 12 * 60 * 60 * 1000 - (Date.now() - unlockTime)
        if (newRemaining > 0) {
          updateTimeRemaining(newRemaining)
        } else {
          clearInterval(timer)
          isUnlocked.value = false
          storage.remove(['unlockCode', 'unlockTime', 'isUnlocked'])
        }
      }, 1000)
    } else {
      isUnlocked.value = false
      storage.remove(['unlockCode', 'unlockTime', 'isUnlocked'])
    }
  } else {
    isUnlocked.value = false
  }
}

// 处理解锁
async function handleUnlock() {
  const code = unlockCode.value.trim().split(/[\s,;]+/).filter(Boolean)[0] || ''
  
  if (!code) {
    showStatus('请输入解锁码', 'error')
    return
  }

  isVerifying.value = true
  statusMessage.value = ''

  try {
    const result = await verifyUnlockCode(code)
    
    if (!result.success) {
      showStatus(result.message, 'error')
      isVerifying.value = false
      return
    }

    // 成功：保存参数
    const unlockTime = Date.now()
    await storage.set({
      unlockCode: code,
      unlockTime: unlockTime,
      isUnlocked: true
    })

    showStatus('解锁成功！', 'success')
    
    setTimeout(() => {
      isUnlocked.value = true
      unlockCode.value = ''
      updateTimeRemaining(12 * 60 * 60 * 1000)
      
      // 启动倒计时
      timer = setInterval(() => {
        const newRemaining = 12 * 60 * 60 * 1000 - (Date.now() - unlockTime)
        if (newRemaining > 0) {
          updateTimeRemaining(newRemaining)
        } else {
          clearInterval(timer)
          isUnlocked.value = false
          storage.remove(['unlockCode', 'unlockTime', 'isUnlocked'])
        }
      }, 1000)
    }, 600)
  } catch (error) {
    showStatus('网络异常，请稍后重试', 'error')
    isVerifying.value = false
  }
}

function showStatus(message, type) {
  statusMessage.value = message
  statusType.value = type
}

function updateTimeRemaining(ms) {
  const hours = Math.floor(ms / (60 * 60 * 1000))
  const minutes = Math.floor((ms % (60 * 60 * 1000)) / (60 * 1000))
  const seconds = Math.floor((ms % (60 * 1000)) / 1000)
  
  timeRemaining.value = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 窗口控制函数
function handleWindowMinimize(e) {
  if (e) {
    e.preventDefault()
    e.stopPropagation()
  }
  emit('window-minimize')
}

function handleWindowMaximize(e) {
  if (e) {
    e.preventDefault()
    e.stopPropagation()
  }
  emit('window-maximize')
}

function handleWindowClose(e) {
  if (e) {
    e.preventDefault()
    e.stopPropagation()
  }
  emit('window-close')
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.unlock-container {
  width: 100%;
  height: 100%;
  min-height: calc(100vh - 40px);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
  background: #f7f7f2;
  color: #1a1a1a;
  padding: 30px 25px;
  -webkit-app-region: no-drag;
}

.header {
  text-align: center;
  margin-bottom: 40px;
  padding: 24px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.06);
  position: relative;
}

/* Electron 环境下的沉浸式头部 */
.header.electron-header {
  -webkit-app-region: drag;
  padding-left: 12px;
  padding-right: 12px;
}

.header.electron-header .header-content {
  -webkit-app-region: drag;
}

.header.electron-header .window-controls {
  -webkit-app-region: no-drag !important;
}

.header-content {
  position: relative;
  z-index: 1;
}

/* 窗口控制按钮 */
.window-controls {
  display: flex !important;
  align-items: center;
  gap: 8px;
  position: absolute;
  top: 12px;
  left: 12px;
  -webkit-app-region: no-drag;
  z-index: 10000;
  flex-shrink: 0;
  visibility: visible;
  opacity: 1;
  pointer-events: auto;
}

.window-button {
  width: 28px;
  height: 28px;
  border-radius: 6px;
  border: 1px solid rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.15s ease;
  padding: 0;
  margin: 0;
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  background: #ffffff;
  pointer-events: auto;
  user-select: none;
  -webkit-user-select: none;
}

.window-button:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.4);
}

.window-button:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.window-button-close {
  background: #ff5f57;
  border-color: rgba(0, 0, 0, 0.2);
}

.window-button-close:hover:not(:disabled) {
  background: #ff3b30;
}

.window-button-minimize {
  background: #ffbd2e;
  border-color: rgba(0, 0, 0, 0.2);
}

.window-button-minimize:hover:not(:disabled) {
  background: #ff9500;
}

.window-button-maximize {
  background: #28c840;
  border-color: rgba(0, 0, 0, 0.2);
}

.window-button-maximize:hover:not(:disabled) {
  background: #1fb832;
}

.window-button svg {
  width: 11px;
  height: 11px;
  pointer-events: none;
  stroke: rgba(0, 0, 0, 0.8);
  stroke-width: 1.8;
  fill: none;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.logo-container {
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
}

#logo-canvas {
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
}

h1 {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
  letter-spacing: 1px;
  color: #ffffff;
}

.subtitle {
  font-size: 14px;
  opacity: 0.9;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 300;
}

.section {
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  opacity: 0.95;
}

input[type="text"] {
  width: 100%;
  padding: 12px 16px;
  font-size: 14px;
  border: 1px solid rgba(0, 0, 0, 0.12);
  border-radius: 8px;
  background: #ffffff;
  color: #1a1a1a;
  transition: all 0.3s ease;
}

input[type="text"]::placeholder {
  color: rgba(0, 0, 0, 0.4);
}

input[type="text"]:focus {
  outline: none;
  border-color: rgba(0, 0, 0, 0.3);
  background: #ffffff;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
}

.hint {
  font-size: 12px;
  margin-top: 6px;
  opacity: 0.8;
  line-height: 1.4;
}

.btn {
  width: 100%;
  padding: 14px 20px;
  font-size: 16px;
  font-weight: 600;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-family: inherit;
}

.btn-primary {
  background: #667eea;
  color: #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.btn-primary:hover:not(:disabled) {
  background: #5a62e5;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.btn-primary:active:not(:disabled) {
  transform: translateY(0);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-large {
  padding: 16px 20px;
  font-size: 18px;
}

.status-message {
  margin-top: 15px;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  text-align: center;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.status-message.error {
  background: #ffe5e7;
  color: #b00020;
  border: 1px solid #ffcdd2;
}

.status-message.success {
  background: #e6f4ea;
  color: #1b5e20;
  border: 1px solid #c8e6c9;
}

.status-success {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  margin-bottom: 20px;
  background: rgba(52, 199, 89, 0.2);
  border-radius: 8px;
  border: 1px solid rgba(52, 199, 89, 0.3);
  font-size: 16px;
  font-weight: 500;
}

.status-success svg {
  color: #4caf50;
}

.info-text {
  margin-top: 20px;
  text-align: center;
  font-size: 13px;
  opacity: 0.85;
}

.info-text p {
  margin: 0;
}

#time-remaining {
  font-weight: 600;
  color: #1a1a1a;
}
</style>

